package com.tencent.yumeko;

import com.tencent.cloud.common.constant.MetadataConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;

@RestController
@RequestMapping("/producer")
public class GatewayRpcProducerController {
    private static Logger LOG = LoggerFactory.getLogger(GatewayRpcProducerController.class);

    @Value("${server.port:0}")
    private int port;

    /**
     * 获取生产者信息.
     *
     * @return information of callee
     */
    @RequestMapping("/info")
    public String info() {
        LOG.info("Gateway Example Produce [{}] is called.", port);
        return String.format("Gateway Example Produce [%s] is called.", port);
    }

    /**
     * 获取 HTTP 标头中的元数据.
     *
     * @param metadataStr metadata string
     * @return metadata in HTTP header
     * @throws UnsupportedEncodingException encoding exception
     */
    @RequestMapping("/echo")
    public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
            throws UnsupportedEncodingException {
        LOG.info(URLDecoder.decode(metadataStr, UTF_8));
        return URLDecoder.decode(metadataStr, UTF_8);
    }
}
